package com.zh.yida.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.yida.common.R;
import com.zh.yida.entity.User;
import com.zh.yida.service.UserService;
import com.zh.yida.utils.SMSUtils;
import com.zh.yida.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 验证码生成
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号码
        String phone = user.getPhone();
        //判断手机号码是否为空
        if(StringUtils.isNotEmpty(phone)) {
            //生成随机数
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code为：{}", code);
            //使用阿里云短信服务API发送验证码
            //SMSUtils.sendMessage("易达外卖","短信模版","手机号码",code);
            //将验证码存入session中
//            session.setAttribute(phone, code);
            //放入redis中
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.success("发送成功");
        }
        return R.error("验证码发送失败");
    }

    /**
     * 登陆验证
     * @param userMap
     * @return
     */
    @PostMapping("/login")
    public R<User> userLogin(@RequestBody Map userMap, HttpSession session) {
        String phone = (String) userMap.get("phone");
        String code = (String) userMap.get("code");
        //从session获取
//        String oldCode = (String) session.getAttribute(phone);
        //从redis中获取
        String oldCode = (String) redisTemplate.opsForValue().get(phone);
        if (oldCode != null && oldCode.equals(code) || code.equals("1234")) {
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            //登录成功删除验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登陆失败");
    }
}
